#include <stdio.h>
// #include <string.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "los_task.h"
//#include "los_debug.h"
#include "iot_gpio_ex.h"
#include "iot_gpio.h"
#define LED_OFF 0
#define LED_ON 1
#define LED_SPARK 2
#define LED_NAME_GPIO_5 5
#define LED_SPARK_INTERVAL_TIME 50
int g_ledState; 


void LedGpioInit(void)
// 初始化LED引脚
{
    int ret = IoTGpioInit(LED_NAME_GPIO_5);
    if (ret != 0)
    {
        printf("IoTGpioInit failed :%#x \r\n", ret);
        return;
    }
    /*设置复用为GPIO功能*/
    ret = IoTGpioSetFunc(LED_NAME_GPIO_5, IOT_GPIO_FUNC_GPIO_5_GPIO);
    if (ret != 0)
    {
        printf("IoTGpioSetFunc failed :%#x \r\n", ret);
        return;
    }
    /*设置方向为输出*/
    ret = IoTGpioSetDir(LED_NAME_GPIO_5, IOT_GPIO_DIR_OUT);
    if (ret != 0)
    {
        printf("IoTGpioSetDir failed :%#x \r\n", ret);
        return;
    }
    printf("----- LedGpioInit success! -----\r\n");
}
void LedGpioCtrl(unsigned short ledSta)
{
    switch (ledSta)
    {

    case LED_ON:
    {
        IoTGpioSetOutputVal(LED_NAME_GPIO_5, LED_ON);
        break;
    }
    case LED_OFF:
    {
        IoTGpioSetOutputVal(LED_NAME_GPIO_5, LED_OFF);
        break;
    }
    case LED_SPARK:
    {
        IoTGpioSetOutputVal(LED_NAME_GPIO_5, LED_ON);
        osDelay(LED_SPARK_INTERVAL_TIME);
        IoTGpioSetOutputVal(LED_NAME_GPIO_5, LED_OFF);
        osDelay(LED_SPARK_INTERVAL_TIME);
        IoTGpioSetOutputVal(LED_NAME_GPIO_5, LED_ON);
        osDelay(LED_SPARK_INTERVAL_TIME);
        IoTGpioSetOutputVal(LED_NAME_GPIO_5, LED_OFF);
        break;
    }
    default:
        break;
    }
}
static void GpiooutTask(void)
{
    /*循环检测按键状态并处理*/
    while (1)
    {
        switch (g_ledState)
        {
        case LED_ON:
            g_ledState = LED_SPARK;
            printf("led State : SPART \r\n");
            break;
        case LED_OFF:
            g_ledState = LED_ON;
            printf("led State : ON \r\n");
            break;
        case LED_SPARK:
            g_ledState = LED_OFF;
            printf("led State : OFF \r\n");
            break;
        default:
            g_ledState = LED_OFF;
            break;
        }
        LedGpioCtrl(g_ledState);
        osDelay(LED_SPARK_INTERVAL_TIME);
    }
    return;
}
void GpiooutSamp1e(void)
{
    // 初始化
    LedGpioInit();
    /*设置线程属性*/
    osThreadAttr_t attr;
    attr.name = "GpioutTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;
    attr.priority = 20;
    /*创建定时控制LED灯线程*/
    osThreadId_t threadID1 = osThreadNew((osThreadFunc_t)GpiooutTask, NULL, &attr);
    if (threadID1 = NULL)
    {
        printf("Falied to create GpiooutTask!\r\n");
    }
}
APP_FEATURE_INIT(GpiooutSamp1e);